﻿<?
	require_once "DB.php";	
	require_once "../db/Recordset.cls";	
	 
	function db($connId=""){
	 	
		$connections["rip"] = 'mysql://root@localhost/rip' ;
		
		if ($connId=="") $connId	= "rip";
		 
		$connstring = $connections[$connId] ; 
		return DB::connect($connstring);
	}	
	
	function rs($sql, $parameters="", $connId="",$immediate=true, $startLimit=0,$endLimit=0){
		
		$db = db($connId); 
		
		
		$rs=new Recordset($db,$sql, $parameters, $immediate, $startLimit,$endLimit);
		 
		return $rs;
	}
	
	function sqlExecute($sql,$connId=""){
		if($sql == "") return FALSE;
		$db = db($connId);
		$res = $db->query($sql);
		if (get_class($res)=='db_error') {
			if ($GLOBALS['debugger']=='on') {
			    echo "<pre>";print_r($res);exit();
			}
		    
		}
		return $res;
	}
	
	function recordsetToJson(&$recordset,$results=-1,&$sql,&$info="''"){
		$find = array('\\', '"', '/', "\b", "\f", "\n", "\r", "\t", "\u");
		$repl = array('\\\\', '\"', '\/', '\b', '\f', '\n', '\r', '\t', '\u');
		 
		$output = "[";
		$i = 0;
		while ($values = $recordset->getRow()) {
			$i++;
			
			if($i==1) $output.= "{";
			else $output.= ",{";
			
			foreach($values as $key => $value) {
				$value = str_replace($find, $repl, $value);
				$output.= '"'.$key.'":"'.$value.'",';
			}
			
			$output.= "rowId:$i}";
		}
		 
		$output.="]";
		
		if($results==-1) $results=$i;
		return "{ 'info' : $info ,'results': $results, 'rows':$output}";
	}
	
	// last identity
	function lastIdentity($connId=""){
		$db = db($connId);
		$sql = "SELECT @@IDENTITY AS 'Identity'";
		$id=fLookUp($sql, 'Identity');
		return $id;
	}

	// return a recordset as matrix
	function aLookUp($sql){
		$rs = rs($sql);
		if($rs->recordCount>0){
			while($r=$rs->getRow()){
				$a[]=$r;
			}
			return $a;
		}
	}

	// return a recordset as matrix with index based on key field
	function aKeyLookUp($sql, $keyField){
		$rs = rs($sql);
		if($rs->recordCount>0){
			while($r=$rs->getRow()){
				$a[$r[$keyField]]=$r;
			}
			return $a;
		}
	}
	
	// return a recordset as fields array
	function rLookUp($sql){
		$rs = rs($sql);
		if($rs->recordCount>0){
			return $rs->getRow();
		}
	}
	
	// return the value of fd
	function fLookUp($sql, $fd){
		$r = rLookUp($sql);
		return $r[$fd];
	}

	// return a recordset as matrix
	function lLookUp($sql, $fd){
		$rs = rs($sql);
		if($rs->recordCount>0){
			while($r=$rs->getRow()){
				$a[]=$r[$fd];
			}
			return $a;
		}
	}
	 
?>